# 动作封装

import json
import logging

import allure
import requests
from allure_commons.types import AttachmentType

from data.common.action import ActionData


class Basic:
	def get_request(self, port, params=None, data=None):
		"""
		get请求函数，请求方式为get。
		:param port: 接口后半段衔接
		:param params: params请求体
		:param data: data请求体
		:return: 响应内容
		"""
		with allure.step('发送get请求'):
			response = requests.get(url=ActionData.interface + port, headers=ActionData.headers, params=params,
			                        data=data)
			res_loads = json.loads(response.text)
			allure.attach(response.text, name="响应内容", attachment_type=AttachmentType.TEXT)
		return res_loads

	def post_request(self, port, json=None, params=None, data=None):
		"""
		post请求函数，请求方式为post。
		:param port: 接口后半段衔接
		:param json: json请求体
		:param params: params请求体
		:param data: data请求体
		:return: 响应内容
		"""
		with allure.step('发送post请求'):
			response = requests.post(url=ActionData.interface + port, headers=ActionData.headers, json=json,
			                         params=params,
			                         data=data)
			res_loads = json.loads(response.text)
			allure.attach(response.text, name="响应内容", attachment_type=AttachmentType.TEXT)
		return res_loads

	def put_request(self, port, json=None, params=None, data=None):
		"""
		put请求函数，请求方式为put。
		:param port: 接口后半段衔接
		:param json: json请求体
		:param params: params请求体
		:param data: data请求体
		:return: 响应内容
		"""
		with allure.step('发送put请求'):
			response = requests.put(url=ActionData.interface + port, headers=ActionData.headers, json=json,
			                        params=params,
			                        data=data)
			res_loads = json.loads(response.text)
			allure.attach(response.text, name="响应内容", attachment_type=AttachmentType.TEXT)
		return res_loads

	def delete_request(self, port, json=None, params=None, data=None):
		"""
				delete请求函数，请求方式为delete。
				:param port: 接口后半段衔接
				:param json: json请求体
				:param params: params请求体
				:param data: data请求体
				:return: 响应内容
				"""
		with allure.step('发送delete请求'):
			response = requests.delete(url=ActionData.interface + port, headers=ActionData.headers, json=json,
			                           params=params,
			                           data=data)
			res_loads = json.loads(response.text)
			allure.attach(response.text, name="响应内容", attachment_type=AttachmentType.TEXT)
		return res_loads

	def assert_code(self, response, value):
		"""
		断言字段值判断函数。
		:param response: 调用接口返回值
		:param value: 判断值
		:return: True / False "错误信息: {response}"
		"""
		with allure.step('验证响应内容'):
			res_dumps = json.dumps(response)
			if response == value:
				logging.info(res_dumps)
				allure.attach(res_dumps, name="内容验证结果", attachment_type=AttachmentType.TEXT)
				assert True
			else:
				logging.error(res_dumps)
				allure.attach(res_dumps, name="内容验证结果", attachment_type=AttachmentType.TEXT)
				assert False, f"执行错误，预期结果: {value} || 实际结果: {response}"


if __name__ == '__main__':
	pass
